<?php
/**
 * @Author: gml
 * @Date:   2015-12-14 12:48:24
 * @Last Modified by:   gml
 * @Last Modified time: 2016-01-20 09:54:30
 */
class Url_model extends CI_Model{

    public function __construct(){
        parent::__construct();
    }
    //获取表名
    public function getTable($date) {
	    $date = str_replace('-', '_', $date);
        $db_name = sprintf(URL_CALC_DB, substr($date, 0, 7));
        $table_name = sprintf(URL_CALC_TABLE, $date);
        
	    $chk_sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='{$table_name}'";
        $query = $this->db->query($chk_sql);
        if ($query->num_rows() == 0){
            return false;
        }
	    return '`'.$db_name.'`.`'.$table_name.'`';
    }
    //获取所有渠道
    public function getAllChannel($date) {
        $table_name = $this -> getTable($date);
        if(!$table_name) return false;

        $sql = "SELECT productid as productname FROM %s GROUP BY productname";
        $sql = sprintf($sql, $table_name);
        $result = $this -> db -> query($sql) -> result('array');
        $data = array();
        foreach($result as $item) {
            $key = 'p_' . $item['productname'];
            $data[$key] = $key;
        }
        return $data;
    }

    //URL时长
    public function get_url_list($date, $product_name = '-1',$page = 1, $limit = 100) {
        $offset = ($page -1) * $limit;
        $table_name = $this -> getTable($date);
	    if(!$table_name) return false;

	    $where = '';
        if($product_name != '-1') {
            $where .= ' WHERE `productid` = "'.$product_name.'"';
        }
        $sql = "SELECT * from %s ".$where." ORDER BY time desc  LIMIT %s, %s ";
        $sql = sprintf($sql, $table_name, $offset, $limit);
	    $result = $this -> db -> query($sql) -> result('array');
        if(!$result) return false;
        return $result;
    }

    //获取长度
    public function getCount($date, $product_name = '-1') {
        $table_name = $this -> getTable($date);

        if(!$table_name) return false;

        /*if($product_name != '-1') {
            $this -> db -> where('productid',$product_name);
        }
        $this -> db -> from($table_name);
        return $this -> db -> count_all_results();
        */
        $sql = "SELECT MAX(id) as count FROM ".$table_name;
        $result = $this -> db -> query($sql) -> result('array');
        return $result[0]['count'];
    }
}
